package com.touch.graphingutil;
import java.awt.*;
import java.util.*;
import javax.swing.*;

import com.touch.util.IntTools;
public class JGraph extends JPanel
{
	private static final long serialVersionUID = 4359594985145459957L;	
	protected int top;
	protected int bottom;
	protected int left;
	protected int right;
	protected int titleHeight;
	protected int labelWidth;
	protected FontMetrics fm;
	protected int padding = 4;
	protected String title;
	protected int min;
	protected int max;	
	protected final Vector <GraphItem> items = new Vector <GraphItem>();
	
	protected JGraph(String title, int min, int max)
	{
		this.title = title;
	    this.min = min;
	    this.max = max;	    
	}
	
   @SuppressWarnings("deprecation")
   public void reshape(int x, int y, int width, int height) 
   {
      super.reshape(x, y,width, height);
      this.fm = this.getFontMetrics(getFont());
      this.titleHeight = this.fm.getHeight();
      this.labelWidth = Math.max(this.fm.stringWidth(new Integer(min).toString()),
      this.fm.stringWidth(new Integer(max).toString())) + 2;
	  this.top = this.padding + this.titleHeight;	  
	  this.bottom = this.getSize().height - this.padding;
	  this.left = this.padding + this.labelWidth;	  
	  this.right = this.getSize().width - this.padding;
   }
   public void paintComponent(Graphics g)
   {
	   super.paintComponent(g);
	   //draw the title
	   this.fm = getFontMetrics(getFont());
	   g.drawString(title, (this.getSize().width - this.fm.stringWidth(title))/2, top);
	   // draw the max and min values
	   g.drawString(IntTools.format(min), padding, bottom);
	   g.drawString(IntTools.format(max), padding, top + titleHeight);
	   // draw the vertical and horizontal lines
	   g.drawLine(left, top, left, bottom);
	   g.drawLine(left, bottom, right, bottom);
   }   
   public void rescale(int min, int max)
   {
	   this.min = min;
	   this.max = max;
   }
   public Dimension preferredSize() 
   {
	   return(new Dimension(300, 200));
   }
   public void setItem(int index, int value)
   {
	   this.items.elementAt(index).value = value;
   }
   public void setItem(int index, int value, Color col)
   {
	   this.items.elementAt(index).value = value;
	   this.items.elementAt(index).color = col;
   }
   public void addItem(String name, int value, Color col) 
   {
	   this.items.addElement(new GraphItem(name, value, col));
   }
   public void addItem(String name, int value) 
   {
	   this.items.addElement(new GraphItem(name, value, Color.black));
   }
   public void removeItem(String name) 
   {
      for (int i = 0; i < items.size(); i++) 
      {
         if (((GraphItem)items.elementAt(i)).title.equals(name))
            items.removeElementAt(i);
      }
   }   
}
